package team.bluepen.order.data.database.mysql;

import space.lingu.light.log.JdkDefaultLogger;
import team.bluepen.order.constant.ErrorCode;
import team.bluepen.order.data.entity.Role;
import team.bluepen.order.data.entity.User;

/**
 * @author RollW
 */
public class UserRepository {
    private final UserDao userDao;

    public UserRepository() {
        UserDatabase database = UserDatabase.getDatabase();
        database.getConnectionPool().setLogger(JdkDefaultLogger.getLogger("User"));
        userDao = database.getUserDao();
    }

    public UserDao getUserDao() {
        return userDao;
    }

    public void createAdmin() {
        User admin = new User("admin", "123456", 1, Role.ADMIN);
        userDao.insert(admin);
    }

    public ErrorCode verifyUser(User user) {
        User queriedUser = userDao.get(user.getUsername());
        if (queriedUser == null) {
            return ErrorCode.ERROR_USER_NOT_EXIST;
        }
        if (!queriedUser.getPassword().equals(user.getPassword())) {
            return ErrorCode.ERROR_PASSWORD_NOT_CORRECT;
        }
        user.setRole(queriedUser.getRole())
                .setId(queriedUser.getId());
        return ErrorCode.SUCCESS;
    }

    public ErrorCode createUser(User user) {
        if (user == null ||
                user.getPassword() == null ||
                user.getUsername() == null ) {
            return ErrorCode.ERROR_NULL;
        }
        if (user.getRole() == null) {
            user.setRole(Role.GUEST);
        }
        User queriedUser = userDao.get(user.getUsername());
        if (queriedUser != null) {
            return ErrorCode.ERROR_USER_EXISTED;
        }
        userDao.insert(user);
        return ErrorCode.SUCCESS;
    }
}
